using Autofac;
using CoreManager.Repository.DbContext;
using CoreManager.Repository.Repositories;
using CoreManager.Services.Auth;
using CoreManager.Core.Caching;
using CoreManager.Core.Captcha;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Reflection;

namespace CoreManager.API.Configuration
{
    /// <summary>
    /// Autofac依赖注入模块
    /// </summary>
    public class DependencyInjectionModule : Autofac.Module
    {
        private readonly IConfiguration _configuration;

        public DependencyInjectionModule(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        protected override void Load(ContainerBuilder builder)
        {
            // 注册配置
            builder.RegisterInstance(_configuration).As<IConfiguration>().SingleInstance();

            // 注册数据库上下文
            RegisterDataAccess(builder);

            // 注册业务服务
            RegisterServices(builder);

            // 注册其他组件
            RegisterOtherComponents(builder);
        }

        /// <summary>
        /// 注册数据访问相关组件
        /// </summary>
        private void RegisterDataAccess(ContainerBuilder builder)
        {
            // 注册EF Core上下文
            builder.RegisterType<CoreManagerDbContext>()
                .AsSelf()
                .InstancePerLifetimeScope()
                .OnActivated(e =>
                {
                    var logger = e.Context.Resolve<ILogger<CoreManagerDbContext>>();
                    logger.LogInformation("CoreManagerDbContext已初始化");
                });

            // 注册通用仓储
            builder.RegisterGeneric(typeof(Repository<>))
                .As(typeof(IRepository<>))
                .InstancePerLifetimeScope()
                .OnActivated(e =>
                {
                    var logger = e.Context.Resolve<ILogger<DependencyInjectionModule>>();
                    logger.LogDebug("仓储已注册: {RepositoryType}", e.Instance.GetType().Name);
                });
        }

        /// <summary>
        /// 注册业务服务
        /// </summary>
        private void RegisterServices(ContainerBuilder builder)
        {
            // 注册认证服务
            /*//builder.RegisterType<JwtService>()
            //    .As<IJwtService>()
            //    .InstancePerLifetimeScope();

            //builder.RegisterType<AuthService>()
            //    .As<IAuthService>()
            //    .InstancePerLifetimeScope();
                
            //// 注册验证码服务
            //builder.RegisterType<CaptchaService>()
            //    .As<ICaptchaService>()
            //    .InstancePerLifetimeScope();*/

            // 自动注册所有服务类
            var serviceAssembly = Assembly.Load("CoreManager.Services");
            builder.RegisterAssemblyTypes(serviceAssembly)
                .Where(t => t.Name.EndsWith("Service") && !t.IsAbstract && !t.IsInterface)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope()
                .PropertiesAutowired()
                .OnActivated(e =>
                {
                    var logger = e.Context.Resolve<ILogger<DependencyInjectionModule>>();
                    logger.LogDebug("服务已注册: {ServiceType}", e.Instance.GetType().Name);
                });
        }

        /// <summary>
        /// 注册其他组件
        /// </summary>
        private void RegisterOtherComponents(ContainerBuilder builder)
        {
            // 注册核心组件
            var coreAssembly = Assembly.Load("CoreManager.Core");
            builder.RegisterAssemblyTypes(coreAssembly)
                .Where(t => t.Name.EndsWith("Helper") || 
                           t.Name.EndsWith("Provider") || 
                           t.Name.EndsWith("Factory") || 
                           t.Name.EndsWith("Service")
                      )
                .AsImplementedInterfaces()
                .AsSelf()
                .InstancePerLifetimeScope()
                .PropertiesAutowired();

            // 注册装饰器模式的组件（如果有的话）
            RegisterDecorators(builder);
        }

        /// <summary>
        /// 注册装饰器
        /// </summary>
        private void RegisterDecorators(ContainerBuilder builder)
        {
            // 示例：缓存装饰器
            // builder.RegisterDecorator<CachingAuthService, IAuthService>();
            
            // 示例：日志装饰器
            // builder.RegisterDecorator<LoggingAuthService, IAuthService>();
        }
    }

    /// <summary>
    /// 条件注册模块
    /// </summary>
    public class ConditionalModule : Autofac.Module
    {
        private readonly IConfiguration _configuration;

        public ConditionalModule(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        protected override void Load(ContainerBuilder builder)
        {
            // 条件注册
        }
    }

    /// <summary>
    /// 环境特定模块 环境注册
    /// </summary>
    public class EnvironmentModule : Autofac.Module
    {
        private readonly string _environmentName;

        public EnvironmentModule(string environmentName)
        {
            _environmentName = environmentName;
        }

        protected override void Load(ContainerBuilder builder)
        {
            switch (_environmentName.ToLower())
            {
                case "development":
                    RegisterDevelopmentServices(builder);
                    break;
                case "staging":
                    RegisterStagingServices(builder);
                    break;
                case "production":
                    RegisterProductionServices(builder);
                    break;
            }
        }

        private void RegisterDevelopmentServices(ContainerBuilder builder)
        {
            // 开发环境特定服务
            // builder.RegisterType<DevelopmentEmailService>().As<IEmailService>();
        }

        private void RegisterStagingServices(ContainerBuilder builder)
        {
            // 测试环境特定服务
            // builder.RegisterType<StagingEmailService>().As<IEmailService>();
        }

        private void RegisterProductionServices(ContainerBuilder builder)
        {
            // 生产环境特定服务
            // builder.RegisterType<ProductionEmailService>().As<IEmailService>();
        }
    }
}